package com.example.listenerrecorder;

import android.media.MediaRecorder;
import android.os.Environment;
import android.widget.TextView;

import java.io.File;
import java.util.Date;

public class ShakeRecord {
    File soundFile;//录音的文件
    MediaRecorder mediaRecorder;//媒体管理器

    //标记当前的录音状态
    boolean status;

    //下面两个变量用于输出文件时文件名添加当前时间
    Date time;//
    String str_time;

    public ShakeRecord() {
        this.status = false;
    }

    public void StartRecord(TextView textView) {

        System.out.println("开始摇晃录音");
        status = true;
        time = new Date();
        str_time = time.toLocaleString();

        try {
            //获取手机根目录默认地址
            soundFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getCanonicalFile() + "/摇晃录音:" + str_time + ".amr");
            System.out.println("文件地址:" + soundFile);


            mediaRecorder = new MediaRecorder();


            //设置录音的声音来源与麦克风
            System.out.println("设置录音的声音来源.....");
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);

            //设置录制声音的输出格式(必须在设置声音编码格式之前设置)
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

            //设置声音编码格式
            //System.out.println("设置设置声音编码格式.....");
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            // System.out.println("设置AudioEncoder.....");

            //设置输出文件路径
            mediaRecorder.setOutputFile(soundFile.getAbsolutePath());

            // System.out.println("设置OutputFile.....");

            mediaRecorder.prepare();
            // System.out.println("设置prepare.....");

            mediaRecorder.start();
            System.out.println("设置摇晃监听器:正在录音.....");
            textView.setText("摇晃监听器:正在录音");

        } catch (Exception e) {
            System.out.println("异常");
            e.printStackTrace();
        }
    }

    public void EndRecord(TextView textView) {
        System.out.println("结束摇晃录音");
        status = false;
        if (soundFile != null && soundFile.exists()) {

            //停止录音
            mediaRecorder.stop();
            System.out.println("设置摇晃监听器:结束录音.....");

            textView.setText("摇晃监听器:结束录音");
            //资源释放
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }
}
